package Leetcode.Tree;

/**
 * 实现trie 树 L208题
 */
public class Trie {
    private Trie[] childs;
    private final int ALPHA_SIZE = 26;
    private boolean isEnd;
    /** Initialize your data structure here. */
    public Trie() {
        childs = new Trie[ALPHA_SIZE];
    }

    /** Inserts a word into the trie. */
    public void insert(String word) {
        Trie tmp = this;
        for(char i: word.toCharArray()){
            if(tmp.childs[i-'a'] == null){
                tmp.childs[i-'a'] = new Trie();
            }
            //指向下个节点，这就是递归了
            tmp = tmp.childs[i-'a'];
        }
        tmp.isEnd = true;
    }
    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        Trie tmp = this;
        for(char i: word.toCharArray()){
            if(tmp.childs[i-'a'] == null){
                return false;
            }
            tmp = tmp.childs[i-'a'];
        }
        return tmp.isEnd;
    }
    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        Trie tmp = this;
        for(char i: prefix.toCharArray()){
            if(tmp.childs[i-'a'] == null){
                return false;
            }
            tmp = tmp.childs[i-'a'];
        }
        return true;
    }
}
